const express = require('express');
const router = express.Router();
const { Course, Category, User } = require('../models');
const { successResponse, failureResponse } = require('../utils/responses')
const { setKey, getKey } = require('../utils/redis');

// 查询首页
router.get('/', async function(req, res, next) {
  try {
    let data = await getKey('index');
    if (data) {
      return successResponse(res, '成功获取首页数据', JSON.parse(data));
    }
    // 推荐课程，人气课程，入门课程
    const [recommendedCourses, likeCourses, introductoryCourses] = await Promise.all([
      Course.findAll({
        attributes: { exclude: ['CategoryId', 'UserId', 'content'] },
        include: [
          {
            model: Category,
            as: 'category',
            attributes: ['id', 'name']
          },
          {
            model: User,
            as: 'user',
            attributes: ['id', 'username', 'nickname', 'avatar', 'company']
          }
        ],
        where: { recommended: true },
        order: [['id', 'desc']],
        limit: 20
      }),
      Course.findAll({
        attributes: { exclude: ['CategoryId', 'UserId', 'content'] },
        order: [['likesCount', 'desc'], ['id', 'desc']],
        limit: 10
      }),
      Course.findAll({
        attributes: { exclude: ['CategoryId', 'UserId', 'content'] },
        where: { introductory: true },
        order: [['id', 'desc']],
        limit: 10
      })
    ])
    data = {
      recommendedCourses,
      likeCourses,
      introductoryCourses
    }
    // 设置缓存过期
    await setKey('index', data, 30 * 60);
    successResponse(res, '成功获取首页数据', {
      recommendedCourses,
      likeCourses,
      introductoryCourses
    });
  } catch (error) {
    failureResponse(res, error);
  }
});

module.exports = router;
